package com.zyq.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zyq.exception.CustomException;
import com.zyq.mapper.SignInMapper;
import com.zyq.model.common.BaseDto;
import com.zyq.model.common.ResponseBean;
import com.zyq.model.entity.Article;
import com.zyq.model.entity.Topic;
import com.zyq.model.request.ArticleDto;
import com.zyq.model.request.ContentDto;
import com.zyq.model.request.TopicDto;
import com.zyq.service.ISignInService;
import com.zyq.util.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;

import com.zyq.service.ITopicService;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 帖子Controller
 *
 * @author zyq
 * @date 2021-12-08
 */
@Api( tags = "帖子接口")
@RestController
@RequestMapping("/topic")
public class TopicController
{
    @Autowired
    private ITopicService topicService;

    @Autowired
    private UserUtil userUtil;

    @Autowired
    private ISignInService signInService;
    @InitBinder
    protected void init(HttpServletRequest request, ServletRequestDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }
    /**
     * 管理员获取帖子列表
     */
    @ApiOperation("管理员获取帖子列表")
    @GetMapping("/adminTopicList")
    public ResponseBean adminList(TopicDto topic , @RequestHeader String Authorization){
        StringBuilder orderByStr = new StringBuilder();
        if(topic.getSidx()!=null && topic.getSord()!=null){
            orderByStr.append(topic.getSidx());
            orderByStr.append(" ");
            orderByStr.append(topic.getSord());
        }
        PageHelper.startPage(topic.getPageNum(), topic.getPageSize(),orderByStr.toString());
        List<Topic> list = topicService.selectTopicListByAdmin(topic.getTopic());
        PageInfo<Topic> selectPage = new PageInfo<Topic>(list);
        if (list == null || list.size() < 0) {
            throw new CustomException("查询失败(Query Failure)");
        }
        Map<String, Object> result = new HashMap<String, Object>(16);
        result.put("total", selectPage.getTotal());
        result.put("pages", selectPage.getPages());
        result.put("topics", selectPage.getList());
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
    }

    /**
     * 查询帖子列表
     */
    @ApiOperation("用户查询帖子列表")
    @GetMapping("/list")
    public ResponseBean list(ContentDto topic)
    {

        PageHelper.startPage(topic.getPageNum(), topic.getPageSize());
        List<Topic> list = topicService.selectTopicList(topic);
        PageInfo<Topic> selectPage = new PageInfo<>(list);
        if (list == null || list.size() < 0) {
            throw new CustomException("查询失败(Query Failure)");
        }
        Map<String, Object> result = new LinkedHashMap<>(16);
        result.put("total", selectPage.getTotal());
        result.put("pages", selectPage.getPages());
        result.put("data", selectPage.getList());
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
    }

    /**
     * 获取帖子详细信息
     */
    @ApiOperation("获取帖子详细信息")
    @GetMapping(value = "/{id}")
    public ResponseBean getInfo(@PathVariable("id") Long id)
    {
        Map<String, Object> result = new HashMap<String, Object>(16);
        result.put("data", topicService.selectTopicById(id));
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
    }

    /**
     * 新增帖子
     */
    @ApiOperation("新增帖子(回复帖子)")
    @PostMapping
    public ResponseBean add(@RequestBody Topic topic, @RequestHeader  String Authorization)
    {
        topic.setTime(new Date());
        Map<String,Long> map = new HashMap<>();
        if(topicService.insertTopic(topic)>0){
            map.put("topicId",topic.getId());
            return new ResponseBean(HttpStatus.OK.value(), "发布成功", map);
        }
        return new ResponseBean(HttpStatus.OK.value(), "操作失败", null);
    }

    /**
     * 修改帖子
     */
    @ApiOperation("修改帖子")
    @PutMapping
    @RequiresRoles("管理员")
    public ResponseBean edit(@RequestBody Topic topic)
    {
        if(topicService.updateTopic(topic)>0){
            return new ResponseBean(HttpStatus.OK.value(), "操作成功", null);
        }
        return new ResponseBean(HttpStatus.OK.value(), "操作失败", null);
    }

    /**
     * 删除帖子
     */
    @ApiOperation("删除帖子")
    @DeleteMapping("/{ids}")
    public ResponseBean remove(@PathVariable Long[] ids)
    {
        if(topicService.deleteTopicByIds(ids)>0){
            return new ResponseBean(HttpStatus.OK.value(), "操作成功", null);
        }
        return new ResponseBean(HttpStatus.OK.value(), "操作失败", null);
    }

    /**
     * 查看自己发布的帖子
     */
    @ApiOperation("查看自己发布的帖子")
    @GetMapping("/listByMySelf")
    public ResponseBean listByMySelf(@Validated BaseDto baseDto, @RequestHeader  String Authorization)
    {

        PageHelper.startPage(baseDto.getPageNum(), baseDto.getPageSize());
        List<Topic> list = topicService.selectTopicListByMySelf(userUtil.getUserId());
        PageInfo<Topic> selectPage = new PageInfo<>(list);
        if (list == null || list.size() < 0) {
            throw new CustomException("查询失败(Query Failure)");
        }
        Map<String, Object> result = new LinkedHashMap<>(16);
        result.put("total", selectPage.getTotal());
        result.put("pages", selectPage.getPages());
        result.put("data", selectPage.getList());
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
    }

    /**
     * 签到健康计划帖子
     */
    @ApiOperation("签到健康计划帖子")
    @GetMapping("/signIn")
    public ResponseBean signIn(@RequestHeader  String Authorization,@RequestParam Long topicId)
    {
        Long userId = userUtil.getUserId();
        int day = signInService.getTimes(userId);
        if(signInService.countSignIn(userId,topicId)==0){
            signInService.insertSignIn(userId,topicId);
        }
        return new ResponseBean(HttpStatus.OK.value(), "签到成功", "连续签到第"+day+"天，");
    }

    @ApiOperation("分享到论坛")
    @GetMapping("/share")
    public ResponseBean share(@RequestHeader  String Authorization,@RequestParam Long topicId,@RequestParam String content)
    {
        Topic topic = new Topic()
                .setTime(new Date())
                .setContent(content)
                .setFatherId(topicId)
                .setClassificationId(4L)
                .setUserId(userUtil.getUserId());
//       content : ("我执行了这个健康计划哦，快来和我一起吧");
        topicService.insertTopic(topic);
        return new ResponseBean(HttpStatus.OK.value(), "分享成功",null);
    }
}
